package com.msgc.utils.crypto.aes.dao;

import com.msgc.utils.JsonUtil;
import com.msgc.utils.crypto.aes.entity.AesInfoEntity;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 使用文件实现持久化 AES加密所需信息
 * @author liuyanming
 */
@Service
public class AesInfoFileImpl implements IAesInfoDao {

    private final Charset utf8 = Charsets.UTF_8;

	public String getAesInfoPath() {
		return aesInfoPath;
	}

	public void setAesInfoPath(String aesInfoPath) {
		this.aesInfoPath = aesInfoPath;
	}

	@Value("${msgc.aesInfoPath}")
	String aesInfoPath;

	@Override
	public void save(AesInfoEntity aesInfo) throws Exception {
		if(aesInfo == null) {
			throw new NullPointerException("aesInfo can't be null!");
		}
		String jsonStr = JsonUtil.toJson(aesInfo);
		Files.write(getFilePath(), jsonStr.getBytes(utf8));
	}

	@Override
	public AesInfoEntity get() throws Exception {
		String jsonStr = new String(Files.readAllBytes(getFilePath()), utf8);
		return JsonUtil.toObject(jsonStr, AesInfoEntity.class);
	}

	private Path getFilePath() throws IOException {
		Path fileLocation = Paths.get(aesInfoPath);
		if(Files.notExists(fileLocation)){
			Files.createDirectories(fileLocation);
		}
		String fileName = "aesInfo.json";
		return fileLocation.resolve(fileName);
	}


}
